<?php
declare(strict_types=1);

namespace WebApp\lib;

/**
 * Class EventCenter
 * @package WebApp\lib
 */
class EventCenter
{
    private static $self;
    private function __construct()
    {
    }

    /**
     * @return EventCenter
     */
    public static function getInstance()
    {
        if (!self::$self) {
            self::$self = new self;
        }
        return self::$self;
    }

    private $events = [];

    /**
     * 注册事件
     * @param $id
     * @param $func
     * @return bool
     */
    public function subscribe($id, $func)
    {
        $this->events[$id] = $func;
        return true;
    }

    /**
     * 删除事件
     * @param $id
     * @return bool
     */
    public function unSubscribe($id)
    {
        unset($this->events[$id]);
        return true;
    }

    /**
     * @param $id
     * @param array $params
     * @return mixed
     */
    public function publish($id, ...$params)
    {
        $func = $this->events[$id] ?? false;
        if (is_object($func)) {
            return $func(...$params);
        }
        return null;
    }

    /**
     * @param array $events
     */
    public function setEvents($events)
    {
        $this->events = $events;
    }
}
